package com.th.therp.controller;

import com.th.therp.exception.BaseException;
import com.th.therp.pojo.dto.PurchaseDto;
import com.th.therp.pojo.dto.page.PurchasePageQueryDTO;
import com.th.therp.pojo.result.PageResult;
import com.th.therp.pojo.result.Result;
import com.th.therp.service.PurchaseService;
import jakarta.validation.Valid;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * 采购单请求控制器
 */
@Log4j2
@RestController
@RequestMapping("/purchase")
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;

    @PostMapping
    @ResponseBody
    public Result add(@Valid @RequestBody PurchaseDto purchaseDto, BindingResult bindingResult){
        log.info("新增采购单:{}",purchaseDto);
        if (bindingResult.hasErrors()){
            throw new BaseException("格式不正确");
        }
        purchaseService.add(purchaseDto);
        return Result.success();
    }

    @GetMapping("/page")
    @ResponseBody
    public Result<PageResult> page(PurchasePageQueryDTO purchasePageQueryDTO){
        log.info("采购单分页查询:{}",purchasePageQueryDTO);
        PageResult pageResult = purchaseService.page(purchasePageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping()
    @ResponseBody
    public Result delete(@RequestParam Integer id){
        log.info("采购单退货:{}",id);
        purchaseService.delete(id);
        return Result.success();
    }
}
